package com.lhczf.lucenedb.service;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
@Service
public class DataHub {

    /**
     * 这里面存储的是我们需要处理的业务数据, 阻塞队列
     */
    public static final LinkedBlockingQueue<String> dataQueue = new LinkedBlockingQueue<>();

    /**
     * 当dataQueue的消费者处理完当天的数据，切换目录时，向此队列写入完成的索引目录。
     */
    @Getter
    private ArrayBlockingQueue<String> messageQueue = new ArrayBlockingQueue<>(Runtime.getRuntime().availableProcessors());

    /**
     * 这里面存放的是需要纳入监控范围的线程信息
     */
    private Map<String, Object> monitorThreadsMap = new HashMap<>(16);

    /**
     * 性能信息是否打印的开关
     */
    @Getter
    @Setter
    private boolean performanceDebug = false;

    public void putMessageData(String message) {
        try {
            messageQueue.put(message);
        } catch (InterruptedException e) {
            log.error("插入消息队列时发生了异常，查收数据为：" + message, e);
            Thread.currentThread().interrupt();
        }
    }

    public void putMonitorThreadsMap(String threadId, Object writer) {
        monitorThreadsMap.putIfAbsent(threadId, writer);
    }

    public void removeDataByKey(String key) {
        monitorThreadsMap.remove(key);
    }

    public Object getMonitorThreadsMap(String key) {
        return monitorThreadsMap.get(key);
    }

    public Set<String> getMonitorThreadsMapKeys() {
        return monitorThreadsMap.keySet();
    }
}
